package com.example.tourmemory.subActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.tourmemory.R;
import com.example.tourmemory.data.record.RecordData;
import com.example.tourmemory.data.getdata.RecordDataBank;
import com.example.tourmemory.data.getdata.ScreenShot;

import java.io.File;
import java.util.ArrayList;

public class ShowRecordActivity extends AppCompatActivity {
    public static final int CANCEL = 0;
    public static final int DELETE = 1;

    private RecordData recordData;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_show_record);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 获取当前记录
        Intent intent = getIntent();
        position = intent.getIntExtra("Position", -1);
        recordData = intent.getSerializableExtra("recordData", RecordData.class);
        assert recordData != null;
        recordData.UpdatePicture(this);

        // 设置返回按钮
        ImageView backButton = findViewById(R.id.imageButton_context_back);
        backButton.setOnClickListener(view -> finish());

        // 设置分享按钮
        ImageView shareButton = findViewById(R.id.imageButton_share);
        shareButton.setOnClickListener(view -> shareRecord());

        // 设置删除按钮
        ImageView deleteButton = findViewById(R.id.imageButton_delete);
        deleteButton.setOnClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.warning))
                   .setMessage(getString(R.string.delete_confirm))
                   .setPositiveButton(getString(R.string.confirm), (dialog, which) -> finishWithDeleteRecord(dialog))
                   .setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
            AlertDialog dialog = builder.create();
            dialog.show();
        });

        // 记录的内容
        TextView contextView = findViewById(R.id.textView_context);
        contextView.setText(recordData.getDescription());

        // 记录的时间
        TextView timeView = findViewById(R.id.textView_date_time);
        String dateTime = recordData.getDate(this) + " " + recordData.getTime();
        timeView.setText(dateTime);

        // 记录的地点
        TextView addressView = findViewById(R.id.textView_location);
        String address = recordData.getAddress() + " " + recordData.getPositionName();
        addressView.setText(address);

        // 记录的标签
        TextView tagView = findViewById(R.id.textView_load_tag);
        tagView.setText(recordData.getTag());

        // 初始化图片适配器
        RecyclerView recyclerView = findViewById(R.id.recyclerView_show_pictures);
        ImageAdapter imageAdapter = new ImageAdapter();
        recyclerView.setAdapter(imageAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
    }

    private void finishWithDeleteRecord(DialogInterface dialog){
        dialog.cancel();
        Intent intent = new Intent();
        intent.putExtra("Position", position);
        intent.putExtra("sate", DELETE);
        setResult(RESULT_OK, intent);
        super.finish();
    }

    private void showPicture(Bitmap bitmap, Uri uri) {
        // 弹出显示图片的视图
        LayoutInflater inflater = LayoutInflater.from(this);
        View pictureView = inflater.inflate(R.layout.dialog_show_picture, null);

        // 获取图片视图
        ImageView pictureImageView = pictureView.findViewById(R.id.imageView_show_picture);
        pictureImageView.setImageBitmap(bitmap);

        // 创建并显示对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if(uri.equals(Uri.EMPTY))
            builder.setView(pictureView)
                    .setCancelable(true)
                    .setPositiveButton(getString(R.string.confirm), (dialog, which) -> dialog.cancel());
        else
            builder.setView(pictureView)
                   .setCancelable(false)
                    .setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel())
                   .setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
                       startShare(uri);
                       dialog.cancel();
                   });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void startShare(Uri uri){
        // 创建分享意图
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/png");
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        // 启动分享活动
        startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
    }

    private void shareRecord(){
        // 屏幕截图
        // 获取描述、时间、地点、标签的屏幕截图
        ViewGroup[] viewGroups = {
                findViewById(R.id.viewGroup_description),
                findViewById(R.id.viewGroup_date_time),
                findViewById(R.id.viewGroup_location),
                findViewById(R.id.viewGroup_tag),
        };
        ArrayList<Bitmap> viewBitmaps = new ArrayList<>();
        for (ViewGroup viewGroup : viewGroups) {
            viewBitmaps.add(ScreenShot.GetScreenShot(viewGroup, ScreenShot.WHITE));
        }
        // 拼接描述、时间、地点、标签的屏幕截图
        Bitmap contextBitmap = ScreenShot.ConcatenateBitmapVertical(viewBitmaps);

        // 将足迹的图片拼接为一个网格
        Bitmap pictureBitmap = ScreenShot.ConcatenateFootprintBitmapGrid(recordData);

        // 将描述、时间、地点、标签和图片拼接为一个垂直网格
        ArrayList<Bitmap> recordBitmaps = new ArrayList<>();
        recordBitmaps.add(contextBitmap);
        recordBitmaps.add(pictureBitmap);
        Bitmap bitmap = ScreenShot.ConcatenateBitmapVertical(recordBitmaps);

        // 将位图保存到临时文件
        File file = RecordDataBank.saveBitmapToTempFile(this, bitmap);
        // 获取文件的URI
        Uri uri = RecordDataBank.getFileUri(this, file);
        // 弹出分享对话框
        showPicture(bitmap, uri);
    }

    // 图片适配器
    private class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
        private class ImageViewHolder extends RecyclerView.ViewHolder {
            private final ImageView imageView;

            public ImageViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.imageView_picture_context);
                // 设置点击事件
                itemView.setOnClickListener(view -> {
                    int position = getBindingAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        showPicture(recordData.getBitmap(position), Uri.EMPTY);
                    }
                });
            }
        }

        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.item_show_image_context, parent, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
            holder.imageView.setImageBitmap(recordData.getBitmap(position));
        }

        @Override
        public int getItemCount() {
            return recordData.getPicCount();
        }
    }
}